import cv2
import os
import math

# 消除微小区域
def Big(contours):
    area = 0;
    for i in range(0, len(contours)):
        if (len(contours[i]) < 10):
            area += cv2.contourArea(contours[i])
            for j in range(0, len(contours[i])):
                contours[i][j] = 0
    return area


def partition(arr, low, high):
    i = (low - 1)  # 最小元素索引
    pivot = arr[high]

    for j in range(low, high):

        # 当前元素小于或等于 pivot
        if arr[j] <= pivot:
            i = i + 1
            arr[i], arr[j] = arr[j], arr[i]

    arr[i + 1], arr[high] = arr[high], arr[i + 1]
    return (i + 1)


def quickSort(arr, low, high):
    if low < high:
        pi = partition(arr, low, high)

        quickSort(arr, low, pi - 1)
        quickSort(arr, pi + 1, high)


def statistic(path, ruler):
    if os.path.exists(path):
        whiteArea = 0
        img = cv2.imread(path)
        img = cv2.resize(img, (227, 227), )
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        # 获得灰度为122到255之间的二值图
        # 第二个参数是阈值
        ret, binaryImg = cv2.threshold(gray, 122, 255, cv2.THRESH_BINARY)
        # 轮廓检测函数
        # cv2 binary,contours, hierarchy = cv2.findContours(binaryImg, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
        # cv3
        contours, hierarchy = cv2.findContours(binaryImg, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
        # 绘制轮廓
        whiteArea += Big(contours)
        cv2.drawContours(img, contours, -1, (0, 0, 255), 3)
        Big(contours)
        # cv2.imshow("Image", img)
        # cv2.waitKey(0)
        # cv2.destroyAllWindows()

        height, width = binaryImg.shape
        # cv2.imshow("Image", binaryImg)
        # cv2.waitKey(0)
        # cv2.destroyAllWindows()

        start = []
        end = []
        wid = 0
        line = 0
        for i in range(height):
            flag = 0
            for j in range(width):
                if binaryImg[i, j] != 255:
                    flag = 1
                    wid += 1
                    if not start:
                        start = [i, j]
                    end = [i, j]
            if flag == 1:
                line += 1

        x = abs(end[1] - start[1]) * ruler
        y = abs(end[0] - start[0]) * ruler

        wid = width/line*ruler

        # l是裂缝长度
        l = pow(x**2+y**2,1/2)
        cos = x/l
        sin = y/l
        w = cos * wid
        # ang是裂缝斜度(弧度)
        ang = math.asin(sin)
        for i in range(height):
            for j in range(width):
                if binaryImg[i, j] == 255:
                    whiteArea += 1
        return (227 * ruler * ruler * 227 - ruler * whiteArea), l, w, ang
